package com.itheima.factory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MapperFactory {
private static SqlSessionFactory factory;
private static ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();
    static {
        InputStream in = null;
            try {
                in = Resources.getResourceAsStream("SqlMapConfig.xml");
                SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
                factory = builder.build(in);

            } catch (IOException e) {
                e.printStackTrace();
                throw new ExceptionInInitializerError("初始化SqlSessionFactory失败");
            } finally {
                //释放流对象
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
    }

    public static SqlSession getSqlSession(){
        return factory.openSession(false);
    }

    /**
     * 获取Dao接口的代理实现类
     * @param daoClass dao接口字节码
     * @return
     */
    public static <T> T getMapper(SqlSession sqlSession,Class<T> daoClass){
        //1.判断传入的SqlSession是否为null
        if(sqlSession == null){
            return null;
        }
        //2.不为null，创建代理实现类
        return sqlSession.getMapper(daoClass);
    }
}
